<?php
namespace  Piwik\Plugins\AdsPlace\Lib;
/**
 * Description of API
 *
 * @author Dell
 */
define( 'API_HOST' , "http://54.169.79.122:8080");
//上传图片
define('API_V2_ATTACHMENTS_FORM_UPLOAD', '/v2/attachments/getUserInfo/form/upload');
//define( 'API_UPLOAD_HOST', "http://54.169.79.122:8089/xfplaysignal");
define( 'API_UPLOAD_HOST', "https://tj.xfplay.com/xfplaysignal");

class Apitools {
    private  $key =  'xf@#35b!nv5swr';
    private  $keyId = 'xfmanager';
    
    private $httpClient;
    
    public function __construct() {
        
         $this->httpClient = new ApiRequest(['timeout' => 100]);
    }
    /**
     * 把参数按字母表顺序排序组织成querystring格式
     * 并增加key 参数，最后返回签名好的 query
     * @param Array $params 需要发送在接口的 ？query参数
     * @return String
     */     
    public function getParamsSign($params = [])
    {
        $str = $dot = "";
        $params['ts'] = time();
        $params['keyId'] = $this->keyId;
        ksort($params);
        foreach($params as $key=>$val){
            $str.= $dot .$key ."=".  ($val ); // 不需要urlencode编码
            $dot = "&";
        }
        $query = $str . "&key=". $this->key;
        return  $this->getQueryString($params) ."&sign=" . strtoupper(md5($query)) ;
    }
    /**
     * 请求的键值对 需要进行urlencode编码
     * 但是 计算签名的时候 不需要编码
     * @param type $params
     * @return string
     */
    public function getQueryString( $params ){
        $str = $dot = "";
         foreach($params as $key=>$val){
            $str.= $dot .$key ."=". urlencode ($val ); // 需要urlencode编码
            $dot = "&";
        }
        return $str;
    }
    
    
    /**
     * 发送 数据到接口
     * @param type $method GET/POST
     * @param type $uri  请求的 url地址
     * @param type $arguments 参数@link 具体可以参考 https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html#id2
     *    
     * @return array 用$ret[error][errorCode]>0 判断接口是否成功。=0表示成功。
     */
    public function api_send_request( $method, $uri, $arguments=[])
    {
        $res =  $this->httpClient->api_request( $method , $uri,  $arguments  );
        $contents = $res->getBody()->getContents();
        
         try{
             $ret =  json_decode($contents, true);
         } catch (\InvalidArgumentException $ex) {
             $ret = ['data'=>[],'error'=>['errorCode'=> 10002,'msg'=> $ex->getMessage() ]];
         }
         if(empty($ret)){
             $ret = ['data'=>[],'error'=>['errorCode'=> 10001,'msg'=>'接口返回数据NULL' ]];
         }
         return $ret;   
    }
    /**
     * 用于站点内容请求
     * @param type $method
     * @param type $uri
     * @param type $arguments
     * @return type
     */
    public function http_client_request($method, $uri, $arguments=[])
    {
       $res =  $this->httpClient->api_request( $method , $uri,  $arguments  );
       
       return $res->getBody()->getContents();
       
    }
    /**
     * 把多表单参数上传 发送到 上传接口。
     * @param type $method
     * @param type $uri
     * @param type $arguments
     * @return type string  返回图片的 url地址
     */
    public function api_send_attachment( $method, $uri, $arguments=[])
    {
        $res =  $this->httpClient->api_request( $method , $uri,  $arguments  );
         
        if($res->hasHeader('Location')){
            
            return  ['data'=> $res->getHeader('Location')[0] ,'error'=>['errorCode'=> 0,'msg'=> '上传图片成功'  ]];
        }
        //    foreach ($res->getHeaders() as $name => $values) {
        //        echo $name . ': ' . implode(', ', $values) . "\r\n";
        //    }
         return   $ret = ['data'=>"",'error'=>['errorCode'=> 10001,'msg'=>'接口返回数据NULL' ]];   
    }
    
     public function api_attachments_form_upload( $extension = ".jpg")
     {
         $uri = API_HOST.API_V2_ATTACHMENTS_FORM_UPLOAD."?".$this->getParamsSign( ['contentType'=> $extension]);
          return $this->api_send_request('get', $uri); 
     }
     /**
      * 发送 表单文件 格式数据 ，用于上传图片
      * @param type $params
      * @return type
      */
     public function send_upload_data($params)
     {
         $multipart =[];
         foreach($params  as $key=>$val){
             $multipart[] = [
                 'name'=>$key, 'contents'=> $val,
             ];
         }
        /**
         * 参考文档 https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html#id9
         * 发送 发送表单文件
         */        
         return $this->api_send_attachment('post', API_UPLOAD_HOST, ['multipart'=>$multipart]); 
     }
}
